﻿

@inject IHttpService _httpService
@inject NavigationManager NavigationManager

@inject IPopupService PopupService

<MDialog @bind-Value="Dialog"
         Width="800">
    <MDCard>
        <MCardTitle Class="text-h5">
            添加自定义动态
        </MCardTitle>
        <MCardText>
            填写完毕下方内容后点击保存，再到列表中找到创建的动态，点击编辑，在新的窗口中确认无误后发布
        </MCardText>
        <MCardText>
            <GameNewsEditorCard Model="Model" />

        </MCardText>

        <MCardActions Class="pb-6 pe-6 ps-6 pt-0">
            <MSpacer></MSpacer>
            <CnGalWebSite.Components.Buttons.MasaButton Text="保存" IsAsync="true" OnClick="OnSave" Icon="mdi-check" Rounded/>
        </MCardActions>
    </MDCard>
</MDialog>


@code {

    [Parameter]
    public EventCallback OnRefreshTable { get; set; }

    public EditGameNewsModel Model { get; set; } = new EditGameNewsModel();

    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    bool Dialog { get; set; }

    public async Task OnSave()
    {
        //上传
        try
        {
            //处理数据
            if (string.IsNullOrWhiteSpace(Model.Author) || string.IsNullOrWhiteSpace(Model.Title) || string.IsNullOrWhiteSpace(Model.BriefIntroduction) || string.IsNullOrWhiteSpace(Model.MainPage) || string.IsNullOrWhiteSpace(Model.Link))
            {
                await PopupService.ToastErrorAsync("添加自定义动态失败", "作者，标题，简介，主页，原文链接都必须填写");
                return;
            }


            var obj = await _httpService.PostAsync<EditGameNewsModel, Result>("api/news/AddCustomNews", Model);
            //判断结果
            if (obj.Successful == false)
            {
                await PopupService.ToastErrorAsync("添加自定义动态失败", obj.Error);
            }
            else
            {

                await PopupService.ToastSuccessAsync("添加自定义动态成功", "添加自定义动态成功");

                await OnRefreshTable.InvokeAsync();
                Dialog = false;
            }
        }
        catch (Exception ex)
        {
            await PopupService.ToastErrorAsync("添加自定义动态失败", "添加自定义动态失败");
            //await ErrorHandler.ProcessError(ex, "保存动态数据失败");
        }
    }

    public void Refresh()
    {
        Dialog = true;
        Model = new EditGameNewsModel();

        Model.Type = ArticleType.News;
        Model.PublishTime = DateTime.Now.ToCstTime();

        StateHasChanged();
    }
}
